package hmvictor.jpql;

import java.awt.Component;
import java.awt.Frame;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.openide.util.NbBundle;

/**
 *
 * @author Victor
 */
public class ConnectionDialog extends javax.swing.JDialog {

    private Connection connection;
    
    private Set<String> usedNames=new HashSet<>();

    /**
     * Creates new form ConnectionDialog
     */
    public ConnectionDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        DocumentListener documentListener = new DocumentListener() {
            
            @Override
            public void insertUpdate(DocumentEvent e) {
                validateFields();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                validateFields();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                validateFields();
            }
        };
        nameField.getDocument().addDocumentListener(documentListener);
        userField.getDocument().addDocumentListener(documentListener);
        urlField.getDocument().addDocumentListener(documentListener);
    }
    
    public void setConnection(Connection connection){
        this.connection=connection;
        nameField.setText(connection.getName());
        urlField.setText(connection.getUrl());
        userField.setText(connection.getUser());
    }

    public Connection getConnection() {
        return connection;
    }
    
    protected void validateFields() {
        boolean valid=true;
        List<String> messages=new LinkedList<>();
        if(nameField.getText().trim().isEmpty()) {
            valid=false;
            messages.add("name is required");
        }else{
            if(usedNames.contains(nameField.getText())) {
                valid=false;
                messages.add("name is already used");
            }
        }
        if(urlField.getText().trim().isEmpty()) {
            valid=false;
            messages.add("url is required");
        }
        if(userField.getText().trim().isEmpty()) {
            valid=false;
            messages.add("user is required");
        }
        if(!valid) {
            errors.setText(String.join(",", messages.toArray(new String[0])));
        }else{
            errors.setText(null);
        }
        okButton.setEnabled(valid);
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        okButton = new javax.swing.JButton();
        userField = new javax.swing.JTextField();
        urlField = new javax.swing.JTextField();
        passwordField = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        nameField = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        errors = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.title")); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.jLabel2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.jLabel3.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(okButton, org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.okButton.text")); // NOI18N
        okButton.setEnabled(false);
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        userField.setText(org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.userField.text")); // NOI18N

        urlField.setText(org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.urlField.text")); // NOI18N

        passwordField.setText(org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.passwordField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.jLabel4.text")); // NOI18N

        nameField.setText(org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.nameField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.jButton1.text")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        errors.setFont(errors.getFont().deriveFont((errors.getFont().getStyle() | java.awt.Font.ITALIC)));
        errors.setForeground(new java.awt.Color(255, 0, 0));
        org.openide.awt.Mnemonics.setLocalizedText(errors, org.openide.util.NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.errors.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))
                        .addGap(14, 14, 14)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(passwordField)
                            .addComponent(nameField)
                            .addComponent(urlField)
                            .addComponent(userField)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(errors, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(urlField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(userField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(okButton)
                    .addComponent(errors))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        connection=null;
        setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        connection=null;
        setVisible(false);
    }//GEN-LAST:event_formWindowClosing

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        connection=new Connection(nameField.getText(), urlField.getText(), userField.getText());
        connection.setPassword(passwordField.getPassword());
        setVisible(false);
    }//GEN-LAST:event_okButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConnectionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ConnectionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ConnectionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ConnectionDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ConnectionDialog dialog = new ConnectionDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    public static Connection showNewDialog(Component c, Set<String> usedNames) {
        Frame frame = (Frame) SwingUtilities.getWindowAncestor(c);
        ConnectionDialog dialog=new ConnectionDialog(frame, true);
        dialog.usedNames.addAll(usedNames);
        dialog.setTitle("New Connection");
        dialog.setLocationRelativeTo(frame);
        dialog.okButton.setText(NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.okButton.addText"));
        dialog.getRootPane().setDefaultButton(dialog.okButton);
        dialog.setVisible(true);
        return dialog.getConnection();
    }
    
    public static Connection showEditDialog(Component c, Connection connection, Set<String> usedNames) {
        Frame frame = (Frame) SwingUtilities.getWindowAncestor(c);
        ConnectionDialog dialog=new ConnectionDialog(frame, true);
        dialog.usedNames.addAll(usedNames);
        dialog.setTitle("Edit Connection");
        dialog.setConnection(connection);
        dialog.setLocationRelativeTo(frame);
        dialog.okButton.setText(NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.okButton.updateText"));
        dialog.getRootPane().setDefaultButton(dialog.okButton);
        dialog.setVisible(true);
        return dialog.getConnection();
    }
    
    public static char[] showPasswordDialog(Component c, Connection connection){
        Frame frame = (Frame) SwingUtilities.getWindowAncestor(c);
        ConnectionDialog dialog=new ConnectionDialog(frame, true);
        dialog.setTitle("Input Password");
        dialog.setConnection(connection);
        dialog.nameField.setEditable(false);
        dialog.urlField.setEditable(false);
        dialog.userField.setEditable(false);
        dialog.setLocationRelativeTo(frame);
        dialog.okButton.setText(NbBundle.getMessage(ConnectionDialog.class, "ConnectionDialog.okButton.inputPasswordText"));
        dialog.passwordField.requestFocusInWindow();
        dialog.getRootPane().setDefaultButton(dialog.okButton);
        dialog.setVisible(true);
        return dialog.getConnection() == null? null : dialog.getConnection().getPassword();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel errors;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField nameField;
    private javax.swing.JButton okButton;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JTextField urlField;
    private javax.swing.JTextField userField;
    // End of variables declaration//GEN-END:variables
}
